// config params involved:
// port, open_browser, collect_pattern, page_size, tips_number, preview_height, zoom_rate, session_expires, server_cache, default_filter

var default_config = {port : 8080, open_browser : false, collect_pattern : 'imouto', page_size : 16, tips_number : 5, preview_height : 150, zoom_rate : 2, session_expires : 10, server_cache : 0, default_filter : ''},
config = $.extend({}, default_config),
url = 'http://' + window.location.host + '/json?action=';

function loadConfig() {
	$.ajax({
		async: false,
		url: url + 'config',
		success: function(data, textStatus, jqXHR) {
			for (var key in data) {
				config[key] = data[key];
			}
			showConfig(config);
			if (data.hasCollection) {
				$('.navigation ul').append('<li><a href="./#action=listCollections">Collection</a></li>');
			}
			if (data.hasOther) {
				$('.navigation ul').append('<li><a href="./#action=listOthers">Other</a></li>');
			}
		}
	});
}

function readInput() {
	for (key in config) {
		var $obj = $('#' + key);
		if ($obj.length > 0) {
			if ($obj[0].type == 'checkbox') {
				config[key] = $obj.attr('checked');
			}
			else {
				config[key] = $obj.val();
			}
		}
	}
}

function setConfig() {
	readInput();
	var callback = function(data) {
		if (!data.done)
			alert('set config error');
	};
	$.post(url + 'setConfig', config, callback , 'json');
}

function saveConfig() {
	setConfig();
	var callback = function(data) {
		if (!data.done)
			alert('save config error');
	};
	$.post(url + 'saveConfig', config, callback , 'json');
}

function reloadConfig() {
	$.ajax({
		async: false,
		url: url + 'reloadConfig',
		success: function(data, textStatus, jqXHR) {
			if (data.reload == true) {
				window.location.reload();
			}
		}
	});
}

function showConfig(config) {
	for (key in config) {
		var $obj = $('#' + key);
		if ($obj.length > 0) {
			if ($obj[0].type == 'checkbox') {
				$obj.prop('checked', config[key]);
			}
			else {
				$obj.val(config[key]);
			}
		}
	}
}

$(function() { // onload
	loadConfig();
});